#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

import os
import time
import logging
import random

from aggmon.importer import Importer, ImporterComponent
from basic_types import *

__all__ = ["TestImporter", "TestImporterComponent"]

#TODO: add counter (metrics/second) and register RPC to read counter value


class TestImporter(Importer):
    def __init__( self, hostname=None, sleep=1, count=1000, group_hosts=False, identical=False, random=False, mtype="num", **kwds ):
        Importer.__init__( self, poll_interval_s=sleep, **kwds )
        if hostname == None:
            hostname =  os.uname()[1].split( "." )[0]
        self.count = count
        self.identical = identical
        self.cntr = 0
        self.random = random
        self.mtype = mtype.lower()
        if self.mtype == "log":
            self.name = "test_log"
            self.values = ["OK", "WARNING", "CRITICAL", "UNKNOWN"]
            self.source = "TestImporter"
        elif self.mtype == "job":
            self.name = "test_job"
            self.values = ["queued", "started", "exited"]
            self.source = "Torque"
        else:
            if self.mtype != "num":
                logging.warn( "Unknown metric type %s! Check TestImporter config. Using default!" % str( mtype ) )
                self.mtype = "num"
            self.name = "test_num"
            self.values = range( 0, 9 )
            self.source = "TestImporter"
        if group_hosts:
            self.hosts = [ name.split( "/" )[-1] for name in self.getHierarchy().get_host_names() ]
        else:
            self.hosts = [ hostname ]

    def poll( self ):
        start = int( time.time() )

        logging.info( "---start Metric burst (%d) %d" % (self.count, start) )

        if self.random:
            random.shuffle( self.values )

        for n in range( 0, self.count ):
            value = self.values[ n % len( self.values )]

            if self.mtype == "num":
                name = self.name
                kwds = {}
            if self.mtype == "log":
                name = self.name
                kwds = {"output" : "log output " + str( value )}
            elif self.mtype == "job":
                name = self.name + str( self.cntr )
                kwds = {"start" : int( time.time() - 7200 ), "end" : int( time.time() - 3600 )}
                kwds["cnodes"] = ["sabi36", "sabi37", "sabi35", "sabi15", "sabi16"]
            else:
                assert "unknown metric type"

            for hostname in self.hosts:
                if self.identical:
                        yield Metric( name=name, source=self.source, host=hostname, time=start, value=value[0], **kwds )
                else:
                        yield Metric( name=name, source=self.source, host=hostname, time=int( time.time() ), value=value, **kwds )

        logging.info( "---end burst %d" % time.time() )
        self.cntr+=1


class TestImporterComponent(ImporterComponent):
    def __init__( self, *args, **kwds ):
        ImporterComponent.__init__( self, *args, **kwds)
        self.allowed_kwds.extend( ["hostname", "sleep", "count", "identical", "random", "mtype"] )

    def instantiate( self, *args, **kwds ):
        self.instance = None
        try:
            logging.debug( "instantiating: %s" % self.name )
            self.instance = TestImporter( *args, **kwds )
        except Exception, e:
            raise e
